package com.chenyue.cm.match.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chenyue.cm.account.dao.JdAccountMapper;
import com.chenyue.cm.account.domain.JdAccount;
import com.chenyue.cm.account.service.JdAccountService;
import com.chenyue.cm.account.vo.IntegralSource;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.exception.SysRuntimeException;
import com.chenyue.cm.live.dao.JdLiveMapper;
import com.chenyue.cm.live.dao.JdLiveRecordMapper;
import com.chenyue.cm.live.domain.JdLive;
import com.chenyue.cm.live.domain.JdLiveRecord;
import com.chenyue.cm.live.vo.LiveUser;
import com.chenyue.cm.match.dao.*;
import com.chenyue.cm.match.domain.*;
import com.chenyue.cm.match.service.JdMatchService;
import com.chenyue.cm.match.vo.*;
import com.chenyue.cm.match.vo.param.ThirdSetLiveRoom;
import com.chenyue.cm.user.dao.JdAppUserMapper;
import com.chenyue.cm.user.dao.JdAppUserRoleMapper;
import com.chenyue.cm.user.dao.JdVerifyMapper;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdVerify;
import com.chenyue.cm.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author chenyue-cm
 */
@Service(value = "JdMatchService")
public class JdMatchServiceImpl extends BaseServiceImpl<JdMatch> implements JdMatchService {

    private final JdMatchMapper jdMatchMapper;

    private final JdAppUserMapper jdAppUserMapper;

    private final JdMatchSignMapper jdMatchSignMapper;

    private final JdMatchGroupMapper jdMatchGroupMapper;

    private final JdMatchGroupUserMapper jdMatchGroupUserMapper;

    private final JdMatchFormatMapper jdMatchFormatMapper;

    private final JdMatchTypeMapper jdMatchTypeMapper;

    private final JdAppUserRoleMapper userRoleMapper;

    private final JdLiveRecordMapper jdLiveRecordMapper;

    private final FormatLiveRecordMapper formatLiveRecordMapper;

    private final JdLiveMapper jdLiveMapper;

    private final JdMatchItemRelationMapper jdMatchItemRelationMapper;

    private final PublicAreaMapper publicAreaMapper;

    private final JdVerifyMapper verifyMapper;

    private final ViewMatchGroupUserMapper groupUserMapper;

    private final JdMatchFormatMemberMapper matchFormatMemberMapper;

    private final MatchInfoMapper matchInfoMapper;

    private final JdAccountMapper accountMapper;

    @Resource
    private JdAccountService jdAccountService;

    public JdMatchServiceImpl(
            @Qualifier("jdMatchMapper") JdMatchMapper jdMatchMapper,
            @Qualifier("jdAppUserMapper") JdAppUserMapper jdAppUserMapper,
            @Qualifier("jdMatchSignMapper") JdMatchSignMapper jdMatchSignMapper,
            @Qualifier("jdMatchGroupMapper") JdMatchGroupMapper jdMatchGroupMapper,
            @Qualifier("jdMatchGroupUserMapper") JdMatchGroupUserMapper jdMatchGroupUserMapper,
            @Qualifier("jdMatchFormatMapper") JdMatchFormatMapper jdMatchFormatMapper,
            @Qualifier("jdMatchTypeMapper") JdMatchTypeMapper jdMatchTypeMapper,
            @Qualifier("jdAppUserRoleMapper") JdAppUserRoleMapper userRoleMapper,
            @Qualifier("jdLiveRecordMapper") JdLiveRecordMapper jdLiveRecordMapper,
            @Qualifier("formatLiveRecordMapper") FormatLiveRecordMapper formatLiveRecordMapper,
            @Qualifier("jdLiveMapper") JdLiveMapper jdLiveMapper,
            @Qualifier("jdMatchItemRelationMapper") JdMatchItemRelationMapper jdMatchItemRelationMapper,
            @Qualifier("publicAreaMapper") PublicAreaMapper publicAreaMapper,
            @Qualifier("jdVerifyMapper") JdVerifyMapper verifyMapper,
            @Qualifier("viewMatchGroupUserMapper") ViewMatchGroupUserMapper groupUserMapper,
            @Qualifier("jdMatchFormatMemberMapper") JdMatchFormatMemberMapper matchFormatMemberMapper,
            @Qualifier("matchInfoMapper") MatchInfoMapper matchInfoMapper,
            @Qualifier("jdAccountMapper") JdAccountMapper accountMapper
    ) {
        this.jdMatchMapper = jdMatchMapper;
        this.jdAppUserMapper = jdAppUserMapper;
        this.jdMatchSignMapper = jdMatchSignMapper;
        this.jdMatchGroupMapper = jdMatchGroupMapper;
        this.jdMatchGroupUserMapper = jdMatchGroupUserMapper;
        this.jdMatchFormatMapper = jdMatchFormatMapper;
        this.jdMatchTypeMapper = jdMatchTypeMapper;
        this.userRoleMapper = userRoleMapper;
        this.jdLiveRecordMapper = jdLiveRecordMapper;
        this.formatLiveRecordMapper = formatLiveRecordMapper;
        this.jdLiveMapper = jdLiveMapper;
        this.jdMatchItemRelationMapper = jdMatchItemRelationMapper;
        this.publicAreaMapper = publicAreaMapper;
        this.verifyMapper = verifyMapper;
        this.groupUserMapper = groupUserMapper;
        this.matchFormatMemberMapper = matchFormatMemberMapper;
        this.matchInfoMapper = matchInfoMapper;
        this.accountMapper = accountMapper;
    }

    @Override
    @Resource(name = "jdMatchMapper")
    public void setBaseMapper(LcBaseMapper<JdMatch, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public String checkAddress(Integer matchId, Address address) {
        final String errorMsg = "您只能报名您当前所在的赛事";
        JdMatch match = jdMatchMapper.selectById(matchId);
        if (match == null) {
            return "赛事数据异常";
        }
        if (match.getProvinceCode() != null) {
            if (!address.getProvince().equals(match.getProvinceCode() + "")) {
//                省code 不一致
                return errorMsg;
            }
        }
        if (match.getCityCode() != null) {
            if (!address.getCity().equals(match.getCityCode() + "")) {
//                市code 不一致
                return errorMsg;
            }
        }
        if (match.getAreaCode() != null) {
            if (!address.getArea().equals(match.getAreaCode() + "")) {
//                县code 不一致
                return errorMsg;
            }
        }
        return "";
    }

    /**
     * 按条件查询赛事
     *
     * @param page       当前页
     * @param rows       条数
     * @param type       赛事分类（分类表id）
     * @param matchGroup 参赛范围（1单人/2团体）
     * @param matchType  参赛类型（1单人单项/2单人多项/3多人多项）
     * @param city       当前城市code
     * @param province   当前省会code
     * @return list
     */
    @Override
    public Page<List<MatchInfo>> getAllMatch(Integer page, Integer rows, Integer type, Integer matchGroup, Integer matchType, String keyWords, String city, String province) {
        LambdaQueryWrapper<JdMatch> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdMatch::getState, 1);
        if (null != type && 0 != type) {
            wrapper.eq(JdMatch::getType, type);
        }
        if (null != matchGroup) {
            wrapper.eq(JdMatch::getMatchGroup, matchGroup);
        }
        if (null != matchType) {
            wrapper.eq(JdMatch::getMatchType, matchType);
        }
        if (StringUtils.isNotBlank(keyWords)) {
            wrapper.like(JdMatch::getName, keyWords);
        }
        if (null != city) {
            wrapper.apply("(isnull(province_code) || city_code = " + city + " || (isnull(city_code) && province_code = " + province + "))");
        }
        wrapper.gt(JdMatch::getEndTime, DateUtils.getToday());
        Integer total = jdMatchMapper.selectCount(wrapper);
        Page<List<MatchInfo>> result = new Page<>(page, rows, total);
        //拼接分页语句
        wrapper.last(result.convertPage());
        wrapper.orderByDesc(JdMatch::getCt);
        List<JdMatch> jdMatches = jdMatchMapper.selectList(wrapper);
        List<MatchInfo> resultList = new ArrayList<>();
        if (jdMatches.size() > 0) {
            for (JdMatch jdMatch : jdMatches) {
                MatchInfo matchInfo = matchInfo(jdMatch.getId(), null);
                resultList.add(matchInfo);
            }
        }
        result.setContent(resultList);

        return result;
    }

    @Override
    public Page<List<MatchInfo>> getMatchByUser(Integer page, Integer rows, Integer state, Integer userId, Integer promotionType) {
        LambdaQueryWrapper<JdMatch> wrapper = new LambdaQueryWrapper<>();
        if (0 != state) {
            //前端要求0全部 1待审核 2通过 3拒绝
            wrapper.eq(JdMatch::getState, state - 1);
        }
        if (null != userId) {
            wrapper.eq(JdMatch::getCu, userId);
        }
        Integer total = jdMatchMapper.selectCount(wrapper);
        Page<List<MatchInfo>> result = new Page<>(page, rows, total);
        //拼接分页语句
        wrapper.last(result.convertPage());
        wrapper.orderByDesc(JdMatch::getCt);
        List<JdMatch> jdMatches = jdMatchMapper.selectList(wrapper);
        List<MatchInfo> resultList = new ArrayList<>();
        for (JdMatch jdMatch : jdMatches) {
            MatchInfo matchInfo = matchInfo(jdMatch.getId(), promotionType);
            matchInfo.setState(matchInfo.getState() + 1);
            resultList.add(matchInfo);
        }
        result.setContent(resultList);

        return result;
    }

    @Override
    public MatchInfo matchInfo(Integer matchId, Integer promotionType) {
        JdMatch jdMatch = jdMatchMapper.selectById(matchId);
        if (jdMatch == null) {
            return null;
        }
        final LambdaQueryWrapper<MatchInfo> eq = new LambdaQueryWrapper<MatchInfo>()
                .eq(MatchInfo::getId, matchId);
        if (promotionType != null) {
            eq.eq(MatchInfo::getPromotionType, promotionType);
        }
        MatchInfo matchInfo = matchInfoMapper.selectOne(eq);
        //单个赛事详情
        matchInfo.setMatchArea(
                (StringUtils.isNotBlank(jdMatch.getProvince()) ? jdMatch.getProvince() : "") +
                        (StringUtils.isNotBlank(jdMatch.getCity()) ? jdMatch.getCity() : "") +
                        (StringUtils.isNotBlank(jdMatch.getArea()) ? jdMatch.getArea() : "")
        );
        //比赛分类
        matchInfo.setType(jdMatchTypeMapper.selectById(jdMatch.getType()).getId().toString());
        //参赛类型
        if (1 == jdMatch.getMatchType()) {
            matchInfo.setMatchType("单人单项比赛");
        } else if (2 == jdMatch.getMatchType()) {
            matchInfo.setMatchType("单人多项比赛");
        } else {
            matchInfo.setMatchType("多人多项比赛");
        }
        //参赛范围
        if (1 == jdMatch.getMatchGroup()) {
            matchInfo.setMatchGroup("单人");
        } else {
            matchInfo.setMatchGroup("团体");
        }
        matchInfo.setIntegral(jdMatch.getIntegral());
        //第一个赛程的直播间分配详情
        LambdaQueryWrapper<FormatLiveRecord> liveWrapper = new LambdaQueryWrapper<>();
        liveWrapper.eq(FormatLiveRecord::getMatchId, matchInfo.getId());
        matchInfo.setLiveNum(formatLiveRecordMapper.selectCount(liveWrapper));
        //直播间列表
        List<LiveUser> liveInfoList = new ArrayList<>();
        List<FormatLiveRecord> jdLiveRecords = formatLiveRecordMapper.selectList(liveWrapper);
        for (FormatLiveRecord record : jdLiveRecords) {
            LiveUser liveInfo = new LiveUser();
            liveInfo.setLiveId(record.getLiveId());
            liveInfo.setLiveName(record.getTitle());
            final JdAppUser jdAppUser = jdAppUserMapper.selectById(record.getUserId());
            liveInfo.setLiveUser(jdAppUser.getUserName());
            liveInfo.setHeadImg(jdAppUser.getHeadImg());
            liveInfo.setLiveLogo(record.getLiveLogo());
            liveInfoList.add(liveInfo);
        }
        matchInfo.setLiveList(liveInfoList);

        return matchInfo;
    }

    /**
     * 个人报名
     *
     * @param mobile     手机号
     * @param matchId    赛事id
     * @param checkState 公开赛 1 else 0
     * @param payType    支付状态 0 免费
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void personSign(String mobile, Integer matchId, Integer checkState, Integer payType) {
        LambdaQueryWrapper<JdAppUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(JdAppUser::getMobile, mobile).last(" limit 1 ");
        JdAppUser user = jdAppUserMapper.selectOne(userWrapper);
        LambdaQueryWrapper<JdMatchSign> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdMatchSign::getUserId, user.getId())
                .eq(JdMatchSign::getMatchId, matchId).last(" limit 1");
        JdMatchSign matchSign = jdMatchSignMapper.selectOne(wrapper);
        if (null != matchSign) {
            throw new SysRuntimeException("请勿重复报名");
        } else {
            JdMatchSign personSign = new JdMatchSign();
            personSign.setUserId(Integer.valueOf(user.getId()));
            personSign.setMatchId(matchId);
            personSign.setCt(DateUtils.getToday());
            personSign.setState(checkState);
            personSign.setPayState(payType == 0 ? 1 : 0);
            jdMatchSignMapper.insert(personSign);
            if(payType == 0){
                // 参赛给积分
                JdMatch jdMatch = jdMatchMapper.selectById(matchId);
                jdAccountService.integralRecharge(Integer.valueOf(user.getId()),jdMatch.getIntegral(), IntegralSource.COMPETITON,matchId.toString(),"参赛获得积分");
            }
            if (checkState == 1) {
                enterNextFormat(checkState, personSign.getMatchId(), personSign.getUserId(), personSign.getGroupId());
            }
        }
    }

    /**
     * 团队报名
     *
     * @param groupSignIn 团队报名 入参
     * @param matchId     赛事id
     * @param checkState  公开赛 1 else 0
     * @param payType     支付状态 0 免费
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void teamSign(GroupSignIn groupSignIn, Integer matchId, Integer checkState, Integer payType) {
        //队员列表
        List<GroupSignIn.TeamUser> teamUserList = groupSignIn.getTeamUserList();
        //队员手机号列表
        List<String> groupUserMobile = teamUserList.stream().map(GroupSignIn.TeamUser::getMobile).collect(Collectors.toList());
        //队长手机号
        groupUserMobile.add(groupSignIn.getMobile());
        final Integer leader = Integer.valueOf(getJdAppUser(groupSignIn.getMobile()).getId());

        //创建团队
        JdMatchGroup group = jdMatchGroupMapper.selectOne(
                new LambdaQueryWrapper<JdMatchGroup>()
                        .eq(JdMatchGroup::getMatchId, matchId)
                        .eq(JdMatchGroup::getLeader, leader)
        );
        if (group == null) {
            group = new JdMatchGroup();
            group.setMatchId(matchId);
            group.setName(groupSignIn.getTeamName());
            group.setCount(teamUserList.size() + 1);
            group.setLeader(leader);
            jdMatchGroupMapper.insert(group);
        }
        //添加队员 包括队长
        JdMatchGroupUser groupUser = new JdMatchGroupUser();
        groupUser.setGroupId(group.getId());
        for (String mobile : groupUserMobile) {
//            查看报名成员是否在组队列表里
            JdAppUser user = getJdAppUser(mobile);
            if (user == null) {
                throw new SysRuntimeException("用户：" + mobile + "不存在！");
            }
            final JdMatchGroupUser matchGroupUser = jdMatchGroupUserMapper.selectOne(
                    new LambdaQueryWrapper<JdMatchGroupUser>()
                            .eq(JdMatchGroupUser::getUserId, user.getId())
                            .eq(JdMatchGroupUser::getGroupId, group.getId())
            );

            if (matchGroupUser == null) {
//            不在 添加
                groupUser.setUserId(Integer.valueOf(user.getId()));
                JdVerify verify = verifyMapper.selectOne(new QueryWrapper<JdVerify>()
                        .lambda()
                        .eq(JdVerify::getUserId, groupUser.getUserId())
                        .last(" limit 1")
                );
                groupUser.setMemberName(verify != null ? verify.getName() : user.getUserName());
                groupUser.setCreateTime(DateUtils.getToday());
                jdMatchGroupUserMapper.insert(groupUser);
            }
            JdMatch jdMatch = jdMatchMapper.selectById(matchId);
            jdAccountService.integralRecharge(Integer.valueOf(user.getId()),jdMatch.getIntegral(), IntegralSource.COMPETITON,matchId.toString(),"参赛获得积分");

//            检查是否重复报名
            JdMatchSign matchSign = jdMatchSignMapper.selectOne(new QueryWrapper<JdMatchSign>()
                    .lambda()
                    .eq(JdMatchSign::getUserId, user.getId())
                    .eq(JdMatchSign::getMatchId, matchId)
                    .ne(JdMatchSign::getState, 2)
                    .last(" limit 1"));
            if (null != matchSign) {
                throw new SysRuntimeException("请勿重复报名");
            } else {
                JdMatchSign personSign = new JdMatchSign();
                personSign.setUserId(Integer.valueOf(user.getId()));
                personSign.setGroupId(group.getId());
                personSign.setMatchId(matchId);
                personSign.setCt(DateUtils.getToday());
                personSign.setState(checkState);
                personSign.setPayState(payType == 0 ? 1 : 0);
                final int flag = jdMatchSignMapper.insert(personSign);
                // 参赛给积分
                jdAccountService.integralRecharge(Integer.valueOf(user.getId()),jdMatch.getIntegral(), IntegralSource.COMPETITON,matchId.toString(),"参赛获得积分");
                if (flag == 0) {
                    throw new SysRuntimeException("报名失败");
                }
                if (checkState == 1) {
                    enterNextFormat(checkState, personSign.getMatchId(), personSign.getUserId(), personSign.getGroupId());
                }
            }
        }
    }

    private JdAppUser getJdAppUser(String mobile) {
        final JdAppUser mobileUser = jdAppUserMapper.selectOne(new QueryWrapper<JdAppUser>()
                .lambda()
                .eq(JdAppUser::getMobile, mobile)
                .last(" limit 1")
        );
        if (mobileUser == null) {
            return jdAppUserMapper.selectOne(new QueryWrapper<JdAppUser>()
                    .lambda()
                    .eq(JdAppUser::getUserNum, mobile)
                    .last(" limit 1")
            );
        }
        return mobileUser;
    }

    @Override
    public Page<List<TemporaryTeam>> temporaryTeam(Integer page, Integer rows, Integer matchId) {
        List<TemporaryTeam> content = new ArrayList<>();
        LambdaQueryWrapper<JdMatchGroup> groupWrapper = new LambdaQueryWrapper<>();
        groupWrapper.eq(JdMatchGroup::getMatchId, matchId);
        Integer total = jdMatchGroupMapper.selectCount(groupWrapper);
        Page<List<TemporaryTeam>> result = new Page<>(page, rows, total);
        //拼接分页语句
        groupWrapper.last(result.convertPage());
        List<JdMatchGroup> jdMatchGroups = jdMatchGroupMapper.selectList(groupWrapper);
        if (jdMatchGroups.size() > 0) {
            for (JdMatchGroup jdMatchGroup : jdMatchGroups) {
                //已組隊人數
                LambdaQueryWrapper<JdMatchGroupUser> memberWrapper = new LambdaQueryWrapper<>();
                memberWrapper.eq(JdMatchGroupUser::getGroupId, jdMatchGroup.getId());
                Integer count = jdMatchGroupUserMapper.selectCount(memberWrapper);

                TemporaryTeam team = new TemporaryTeam();
                team.setTeamId(jdMatchGroup.getId());
                team.setLeaderId(jdMatchGroup.getLeader());
                JdAppUser leader = jdAppUserMapper.selectById(jdMatchGroup.getLeader());
                team.setLeaderName(leader.getUserName());
                team.setLeaderHeadImg(leader.getHeadImg());
                team.setTeamName(jdMatchGroup.getName());
                team.setTeamUserNum(count);
                team.setRequiredNum(Math.max((jdMatchGroup.getCount() - count), 0));
                content.add(team);
            }
        }
        result.setContent(content);
        return result;
    }

    @Override
    public TemporaryTeam temporaryTeamByUser(Integer matchId, Integer userId) {
        TemporaryTeam result = new TemporaryTeam();
        result.setMatchInfo(matchInfo(matchId, null));
        LambdaQueryWrapper<JdMatchGroup> groupWrapper = new LambdaQueryWrapper<>();
        groupWrapper.eq(JdMatchGroup::getMatchId, matchId)
                .eq(JdMatchGroup::getLeader, userId).last("limit 1");
        JdMatchGroup jdMatchGroup = jdMatchGroupMapper.selectOne(groupWrapper);
        if (null != jdMatchGroup) {
            result.setTeamId(jdMatchGroup.getId());
            result.setTeamName(jdMatchGroup.getName());
            LambdaQueryWrapper<JdMatchGroupUser> groupUser = new LambdaQueryWrapper<>();
            groupUser.eq(JdMatchGroupUser::getGroupId, jdMatchGroup.getId());
            //已有人数
            Integer count = jdMatchGroupUserMapper.selectCount(groupUser);
            result.setTeamUserNum(count);
            //还需要人数
            result.setRequiredNum(jdMatchGroup.getCount() - count);
            List<TemporaryTeam.TeamUserInfo> teamUser = new ArrayList<>();
            List<JdMatchGroupUser> jdMatchGroupUsers = jdMatchGroupUserMapper.selectList(groupUser);
            List<Integer> userIds = jdMatchGroupUsers.stream().distinct().map(JdMatchGroupUser::getUserId).collect(Collectors.toList());
            List<JdAppUser> jdAppUsers = new ArrayList<>();
            if (userIds.size() > 0) {
                jdAppUsers = jdAppUserMapper.selectBatchIds(userIds);
            }
            for (JdAppUser jdAppUser : jdAppUsers) {
                TemporaryTeam.TeamUserInfo teamUserInfo = new TemporaryTeam.TeamUserInfo();
                teamUserInfo.setUserId(Integer.valueOf(jdAppUser.getId()));
                teamUserInfo.setUserName(jdAppUser.getUserName());
                teamUserInfo.setUserNum(jdAppUser.getUserNum());
                teamUserInfo.setUserPhone(jdAppUser.getMobile());
                teamUserInfo.setUserHeadImg(jdAppUser.getHeadImg());
                teamUser.add(teamUserInfo);
            }
            result.setTeamUserInfo(teamUser);
        }
        return result;
    }

    @Override
    public Success<String> joinTeam(Integer userId, Integer teamId, Integer matchId) {
        LambdaQueryWrapper<JdMatchGroupUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(JdMatchGroupUser::getGroupId, teamId)
                .eq(JdMatchGroupUser::getUserId, teamId);
        List<JdMatchGroupUser> jdMatchGroupUsers = jdMatchGroupUserMapper.selectList(userWrapper);
        if (jdMatchGroupUsers.size() > 0) {
            return Success.error("用户已加入该队伍");
        }
        //校验
        String msg = checkUserCreate(userId, matchId);
        if (StringUtils.isNotEmpty(msg)) {
            return Success.error(msg);
        } else {
            LambdaQueryWrapper<JdMatchGroupUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JdMatchGroupUser::getGroupId, teamId);
            Integer in = jdMatchGroupUserMapper.selectCount(wrapper);
            Integer total = jdMatchGroupMapper.selectById(teamId).getCount();
            if (total - in > 0) {
                JdMatchGroupUser groupUser = new JdMatchGroupUser();
                groupUser.setUserId(userId);
                groupUser.setGroupId(teamId);
                groupUser.setMemberName(jdAppUserMapper.selectById(userId).getUserName());
                groupUser.setCreateTime(DateUtils.getToday());
                jdMatchGroupUserMapper.insert(groupUser);
                return Success.success("加入队伍成功", "");
            } else {
                return Success.error("该队伍已满");
            }
        }
    }

    /**
     * 删除队伍成员
     *
     * @param teamId 队伍id
     * @param userId 队员用户id
     */
    @Override
    public void deleteTeamSignUser(Integer teamId, Integer userId) {
        jdMatchGroupUserMapper.delete(
                new LambdaQueryWrapper<JdMatchGroupUser>()
                        .eq(JdMatchGroupUser::getGroupId, teamId)
                        .eq(JdMatchGroupUser::getUserId, userId)
        );
    }

    @Override
    public String checkUserCreate(Integer userId, Integer matchId) {
        //是否已经报名
        LambdaQueryWrapper<JdMatchSign> signWrapper = new LambdaQueryWrapper<>();
        signWrapper.eq(JdMatchSign::getMatchId, matchId)
                .eq(JdMatchSign::getUserId, userId);
        List<JdMatchSign> jdMatchSigns = jdMatchSignMapper.selectList(signWrapper);
        if (jdMatchSigns.size() > 0) {
            return "已经报名该赛事";
        }
        //是否已发布过临时组队或者参加过
        ViewMatchGroupUser viewMatchGroupUser = groupUserMapper.selectOne(new QueryWrapper<ViewMatchGroupUser>()
                .lambda()
                .eq(ViewMatchGroupUser::getMatchId, matchId)
                .eq(ViewMatchGroupUser::getUserId, userId)
                .last(" limit 1"));
        if (null != viewMatchGroupUser) {
            if (0 == viewMatchGroupUser.getState()) {
                return "已参加该赛事的临时组队";
            } else {
                return "已发布临时组队";
            }
        }
        return "";
    }

    @Override
    public String checkUserSign(Integer userId, Integer matchId) {
        final JdMatch match = jdMatchMapper.selectById(matchId);
        if (match == null) {
            throw new SysRuntimeException("赛事不存在");
        }
        if (match.getMatchGroup() == 1) {
//            单人
            final JdMatchSign sign = jdMatchSignMapper.selectOne(
                    new LambdaQueryWrapper<JdMatchSign>()
                            .eq(JdMatchSign::getMatchId, matchId)
                            .eq(JdMatchSign::getUserId, userId)
            );
            if (sign != null) {
                return "已经报名该赛事，请勿重复报名";
            }
            return "";
        } else {
            final JdMatchGroup group = jdMatchGroupMapper.selectOne(
                    new LambdaQueryWrapper<JdMatchGroup>()
                            .eq(JdMatchGroup::getMatchId, matchId)
                            .eq(JdMatchGroup::getLeader, userId)
            );
            if (group != null) {
                return "已经是队长";
            }
            //当前登陆用户在此赛事 组队身份
            ViewMatchGroupUser viewMatchGroupUser = groupUserMapper.selectOne(new QueryWrapper<ViewMatchGroupUser>()
                    .lambda()
                    .eq(ViewMatchGroupUser::getMatchId, matchId)
                    .eq(ViewMatchGroupUser::getUserId, userId)
                    .last(" limit 1"));
            if (null != viewMatchGroupUser) {
                return "已经报名该赛事";
            }
            return "";
        }
    }

    @Override
    public void createTeam(JdMatchGroup matchGroup) {
        jdMatchGroupMapper.insert(matchGroup);
        JdMatchGroupUser groupUser = new JdMatchGroupUser();
        groupUser.setGroupId(matchGroup.getId());
        groupUser.setUserId(matchGroup.getLeader());
        groupUser.setCreateTime(DateUtils.getToday());
        groupUser.setMemberName(jdAppUserMapper.selectById(matchGroup.getLeader()).getUserName());
        jdMatchGroupUserMapper.insert(groupUser);
    }

    @Override
    public List<MatchSignUserInfo> signUserList(Integer matchId, Integer checkState, Integer payState) {
        List<MatchSignUserInfo> signUserInfoList = new ArrayList<>();
        LambdaQueryWrapper<JdMatchSign> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdMatchSign::getMatchId, matchId);
        if (checkState != null) {
            wrapper.eq(JdMatchSign::getState, checkState);
        }
        if (payState != null) {
            wrapper.eq(JdMatchSign::getPayState, payState);
        }
        List<JdMatchSign> jdMatchSigns = jdMatchSignMapper.selectList(wrapper);
        for (JdMatchSign jdMatchSign : jdMatchSigns) {
            MatchSignUserInfo signUserInfo = new MatchSignUserInfo();
            signUserInfo.setSignId(jdMatchSign.getId());
            JdAppUser jdAppUser = jdAppUserMapper.selectById(jdMatchSign.getUserId());
            signUserInfo.setUserId(Integer.valueOf(jdAppUser.getId()));
            signUserInfo.setUserName(jdAppUser.getUserName());
            signUserInfo.setUserNum(jdAppUser.getUserNum());
            signUserInfo.setUserHeadImg(jdAppUser.getHeadImg());
            signUserInfo.setState(jdMatchSign.getState());
            signUserInfoList.add(signUserInfo);
        }
        return signUserInfoList;
    }

    @Override
    public void signCheck(Integer signId, Integer state) {
        if (null == state) {
            throw new SysRuntimeException();
        }
        JdMatchSign sign = jdMatchSignMapper.selectById(signId);
        sign.setState(state);
        jdMatchSignMapper.updateById(sign);

        if (state == 1) {
            enterNextFormat(state, sign.getMatchId(), sign.getUserId(), sign.getGroupId());
        }
    }

    /**
     * 晋级到下一个赛程
     *
     * @param state   1报名 2晋级
     * @param matchId 赛事id
     * @param userId  用户id
     * @param groupId 团队id
     */
    @Override
    public void enterNextFormat(Integer state, Integer matchId, Integer userId, Integer groupId) {
        final MatchInfo matchInfo = matchInfo(matchId, null);
//        获取当前赛程阶段
        Integer currentFormat = matchInfo.getFormat();
        //        查询下一赛程
        final JdMatchFormat format = jdMatchFormatMapper.selectOne(
                new LambdaQueryWrapper<JdMatchFormat>()
                        .eq(JdMatchFormat::getMatchId, matchId)
                        .eq(JdMatchFormat::getArrangeOrder, state == 1 ? currentFormat : (currentFormat + 1))
                        .last(" limit 1 ")
        );

        final JdMatchFormatMember signRecord = matchFormatMemberMapper.selectOne(
                new LambdaQueryWrapper<JdMatchFormatMember>()
                        .eq(JdMatchFormatMember::getUserId, userId)
                        .eq(JdMatchFormatMember::getFormatId, format.getId())
        );

        if (signRecord == null) {
//            尚未分配到下一赛程
            JdMatchFormatMember member = new JdMatchFormatMember();
            member.setGroupId(groupId);
            member.setUserId(userId);
            member.setFormatId(format.getId());
            matchFormatMemberMapper.insert(member);
        }
    }

    @Override
    public void thirdCreateMatch(ThirdCreateMatch thirdMatch, Integer userId) {
        JdMatch match = new JdMatch();
        match.setId(thirdMatch.getId());
//        团队 - 报名人数
        if (thirdMatch.getMatchGroup() == 1) {
            match.setSignCount(1);
        } else {
            match.setSignCount(thirdMatch.getSignCount());
        }
        BeanUtils.copyProperties(thirdMatch, match);
        match.setAddress(thirdMatch.getMatchArea());
        try {
            if (thirdMatch.getProvinceCode() != null) {
                match.setProvince(publicAreaMapper.selectById(thirdMatch.getProvinceCode()).getName());
                if (thirdMatch.getCityCode() != null) {
                    match.setCity(publicAreaMapper.selectById(thirdMatch.getCityCode()).getName());
                    if (thirdMatch.getAreaCode() != null) {
                        match.setArea(publicAreaMapper.selectById(thirdMatch.getAreaCode()).getName());
                    } else {
                        match.setArea("全市");
                    }
                } else {
                    match.setCity("全省");
                }
            } else {
                match.setProvince("全国");
            }
        } catch (Exception e) {
            throw new SysRuntimeException("地域信息设置有误");
        }
        match.setCu(userId);
        if (match.getId() != null && match.getId() > 0) {
            match.setState(0);
            jdMatchMapper.updateById(match);
        } else {
            match.setCt(DateUtils.getToday());
            //是否中心发布，0不是1是
            match.setIsCenterPush(0);
            //前台发布的赛事默认待审核
            match.setState(0);
            jdMatchMapper.insert(match);
        }
        if (match.getId() != null && match.getId() > 0) {
//            传了id是编辑 旧的先删了
            jdMatchItemRelationMapper.delete(
                    new LambdaQueryWrapper<JdMatchItemRelation>()
                            .eq(JdMatchItemRelation::getMatchId, match.getId())
            );
            jdMatchFormatMapper.delete(
                    new LambdaQueryWrapper<JdMatchFormat>()
                            .eq(JdMatchFormat::getMatchId, match.getId())
            );
//            liveRecord外键关联自动删
        }
        //赛事项目
        String[] matchItems = thirdMatch.getMatchItems().split(",");
        for (String matchItem : matchItems) {
            JdMatchItemRelation relation = new JdMatchItemRelation();
            relation.setMatchId(match.getId());
            relation.setItemId(Integer.parseInt(matchItem));
            jdMatchItemRelationMapper.insert(relation);
        }
        //设置赛程
        if (thirdMatch.getFormats().size() > 3 || thirdMatch.getFormats().size() == 2) {
            throw new SysRuntimeException("赛程设置错误");
        }
        for (ThirdCreateMatch.MatchFormat format : thirdMatch.getFormats()) {
            JdMatchFormat jdMatchFormat = new JdMatchFormat();
            BeanUtils.copyProperties(format, jdMatchFormat);
            jdMatchFormat.setMatchId(match.getId());
            jdMatchFormatMapper.insert(jdMatchFormat);
            //设置每个赛程的直播间
            if (format.getLiveList() == null) {
                continue;
            }
            setLiveRoom(match.getId(), format.getLiveList(), jdMatchFormat.getId());
        }
    }

    /**
     * 三方机构设置直播间
     *
     * @param matchId      赛事id
     * @param liveUserList 直播间信息
     * @param formatId     赛程id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setLiveRoom(Integer matchId, List<FormatLiveRecord> liveUserList, Integer formatId) {
        for (FormatLiveRecord liveUser : liveUserList) {
            if (liveUser.getId() != null && liveUser.getId() > 0) {
                continue;
            }
            final JdLive live = jdLiveMapper.selectById(liveUser.getLiveId());
            if (live == null) {
                continue;
            }
            JdLiveRecord record = new JdLiveRecord();
            record.setMatchId(matchId);
            record.setLiveId(liveUser.getLiveId());
            record.setTitle(liveUser.getTitle());
            record.setLiveLogo(liveUser.getLiveLogo());
            record.setArrangeId(formatId);
            final int success = jdLiveRecordMapper.insert(record);
            if (success == 0) {
                throw new SysRuntimeException(ErrorCode.INSERT_ERROR.getMsg());
            }
        }
    }

    /**
     * 获取直播间
     *
     * @param formatId 赛程id
     * @return ThirdSetLiveRoom
     */
    @Override
    public ThirdSetLiveRoom getLiveRoom(Integer formatId) {
        final ThirdSetLiveRoom liveRoom = new ThirdSetLiveRoom();
        final List<FormatLiveRecord> liveRecords = formatLiveRecordMapper.selectList(
                new LambdaQueryWrapper<FormatLiveRecord>()
                        .eq(FormatLiveRecord::getArrangeId, formatId)
        );
        liveRoom.setLiveUserList(liveRecords);
        liveRoom.setFormatId(formatId);
        return liveRoom;
    }

    /**
     * 根据用户赛事查找团队
     *
     * @param matchId 赛事id
     * @param userId  用户id
     * @return 团队信息
     */
    @Override
    public ViewMatchGroupUser getGroupByUser(Integer matchId, Integer userId) {
        return groupUserMapper.selectOne(
                new LambdaQueryWrapper<ViewMatchGroupUser>()
                        .eq(ViewMatchGroupUser::getMatchId, matchId)
                        .eq(ViewMatchGroupUser::getUserId, userId)
        );
    }

    public static void main(String[] args) {
//        String[] strings = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i"};
//        String randomNumList = getRandomNumList(4, 0, strings.length, strings);
//        System.err.println(randomNumList);

    }
}
